/**
 * 
 */
package sk.kainitram.fuel;

import com.kainitram.morm.Session;
import com.kainitram.morm.SessionBase;

import sk.kainitram.fuel.R.string;
import sk.kainitram.fuel.db.CarContract;
import sk.kainitram.fuel.model.Car;
import sk.kainitram.fuel.model.eFuelType;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * @author Mino develop
 * 
 */
public class NewCarActivity extends Activity {

	private EditText _etSpz;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.newcar);
		initFuelTypes();

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			cancel();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void btnOk_OnClick(View view) {
		Intent data = new Intent();
		if (getParent() == null) {
			onAddCar();
			setResult(Activity.RESULT_OK, data);
		} else {
			getParent().setResult(Activity.RESULT_OK, data);
		}

		finish();
	}

	public void btnCancel_OnClick(View view) {
		cancel();
	}

	private void initFuelTypes() {
		Spinner mySpinner = (Spinner) findViewById(R.id.spFuelType);
		mySpinner.setAdapter(new ArrayAdapter<eFuelType>(this,
				android.R.layout.simple_list_item_1, eFuelType.values()));
		_etSpz = (EditText) findViewById(R.id.etSPZ);
	}

	private void cancel() {
		Intent data = new Intent();
		if (getParent() == null) {
			setResult(Activity.RESULT_CANCELED, data);
		} else {
			getParent().setResult(Activity.RESULT_CANCELED, data);
		}

		finish();
	}

	private void onAddCar() {
		Editable spz = _etSpz.getText();

		Session session = new SessionBase();

		Car newCar = new Car(session);
		newCar.setSpz(spz.toString());

		CarContract.getInstance().InsertCar(newCar, this);
	}

}
